#include "graph.h"
#include "ui_graph.h"
#include "home.h"
#include "ui_home.h"
#include <QtCharts>
#include <QDebug>
#include <QVector>
#include <QMessageBox>
#include<QInputDialog>
#include<QByteArray>
#include <QDesktopServices>
#include<QApplication>
#include <QHBoxLayout>

graph::graph(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::graph)
{
    ui->setupUi(this);
    QChart *chart = new QChart();
       chart->setTitle("Line chart");
       QString name("Series ");
       int nameIndex = 0;
       DataTable m_dataTable = getData();//获得数据
       int maxh,minh,maxz,minz;
       maxh=getmaxh();
       minh=getminh();
       maxz=getmaxz();
       minz=getminz();
       qDebug()<<maxh<<minh<<maxz<<minz;
       for (const DataList &list : m_dataTable) {
           QLineSeries *series = new QLineSeries(chart);//初始化一条折线
           for (const Data &data : list)
               series->append(data.first);//折线添加数据
           series->setName(name + QString::number(nameIndex));//折线设置名字
           nameIndex++;
           chart->addSeries(series);//chart中添加一条折线
       }
       chart->createDefaultAxes();// 创建坐标
       chart->axes(Qt::Horizontal).first()->setRange(minh, maxh);//设置横坐标范围
       chart->axes(Qt::Vertical).first()->setRange(minz, maxz);//设置纵坐标范围
       // Add space to label to add space between labels and axis
       QValueAxis *axisY = qobject_cast<QValueAxis*>(chart->axes(Qt::Vertical).first());
       //利用qobject_cast进行安全转换，将QAbstractAxis类型的变量转换为QValueAxis，为的是在下面使用->setLabelFormat("%.1f  ")
       Q_ASSERT(axisY);//当axisY == 0时，程序会中断
       axisY->setLabelFormat("%.2f  ");//设置坐标的值精确到小数点后2位
   //    chart->legend()->hide();//隐藏图例
       chart->legend()->setAlignment(Qt::AlignTop);//设置图例位置在顶部
       chart->setAnimationOptions(QChart::GridAxisAnimations);//设置动画效果，在第一次显示图表或者更改图标区域大小的时候会显示动画效果

       ui->widget->setChart(chart);
}

graph::~graph()
{
    delete ui;
}
//获得坐标点数据
DataTable graph::getData( ) const
{
    home *ptr = (home*)parentWidget();
return ptr->dataTable;
}
//获得横坐标最大值
int graph::getmaxh( ) const
{
    home *ptr = (home*)parentWidget();
return ptr->maxheng;
}
//获得横坐标最小值
int graph::getminh( ) const
{
    home *ptr = (home*)parentWidget();
return ptr->minheng;
}
//获得纵坐标最大值
int graph::getmaxz( ) const
{
    home *ptr = (home*)parentWidget();
return ptr->maxzong;
}
//获得纵坐标最小值
int graph::getminz( ) const
{
    home *ptr = (home*)parentWidget();
return ptr->minzong;
}
//返回主窗口
void graph::on_return_2_clicked()
{
    this->close();
}
